package com.cskaoyan.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author stone
 * @date 2022/04/26 16:35
 */
@Component
public class CustomAspect {

    //切面类中的方法名任意写

    public void mybefore(JoinPoint joinPoint) {
        System.out.println("hello");
        Object proxy = joinPoint.getThis();   //代理类对象
        Object target = joinPoint.getTarget();//委托类对象
        System.out.println("代理类：" + proxy.getClass());
        System.out.println("委托类："+ target.getClass());

        String methodName = joinPoint.getSignature().getName();
        System.out.println("方法名：" + methodName);

        Object[] args = joinPoint.getArgs();
        System.out.println("参数：" + Arrays.asList(args));
    }

    public void myafter() {
        System.out.println("world");
    }

    //around通知方法类似于InvocationHandler的invoke方法、类似于MethodInterceptor的invoke
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("around通知的前半部分");
        //委托类方法的调用
        //Object proceed = proceedingJoinPoint.proceed();
        Object[] args = proceedingJoinPoint.getArgs();
        if ("add".equals(proceedingJoinPoint.getSignature().getName())) {
            args[0] = 2;
            args[1] = 10;
        }
        Object proceed = proceedingJoinPoint.proceed(args);
        System.out.println("around通知的后半部分");

        return proceed;
    }

    //委托类方法的返回值以形参的方式传入AfterReturning通知方法里
    public void afterReturning(Object result) {
        System.out.println("委托类方法执行的结果：" + result);
    }

    //委托类方法抛出的异常以形参的方式传入AfterThrowing通知方法里
    public void afterThrowing(Exception exception) {
        System.out.println("afterThrowing接收到的异常：" + exception.getMessage());
    }

}
